package service

import (
	"context"
	"encoding/json"
	"github.com/olivere/elastic/v7"
	"math"
	"month/videosvr/internal/models"
	"month/videosvr/video"
	"strconv"
)

const IK_INDEX = `
{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_analyzer": { 
          "tokenizer": "ik_max_word"
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "title": {
        "type": "text",
        "analyzer": "my_analyzer"
      }
    }
  }
}
`

// EsIsIndex todo 判断索引是否已经被创建
func EsIsIndex(index string) (interface{}, error) {
	return models.InitEs(func(client *elastic.Client) (interface{}, error) {
		return client.IndexExists(index).Do(context.Background())
	})
}

// CreateIkIndex todo 创建ik分词器索引
func CreateIkIndex(index string) (interface{}, error) {
	return models.InitEs(func(client *elastic.Client) (interface{}, error) {
		return client.CreateIndex(index).BodyString(IK_INDEX).Do(context.Background())
	})
}

// AddEsVideo todo es添加
func AddEsVideo(index string, video models.Video) (interface{}, error) {
	return models.InitEs(func(client *elastic.Client) (interface{}, error) {
		return client.Index().Index(index).Id(strconv.Itoa(int(video.ID))).BodyJson(video).Do(context.Background())
	})
}

// EsSearch todo 分页搜索
func EsSearch(index string, query *elastic.BoolQuery, high *elastic.Highlight, page int) (int, int, interface{}, error) {
	if page == 0 {
		page = 1
	}
	size := 3 //todo 每页条数
	count, err := models.InitEs(func(client *elastic.Client) (interface{}, error) {
		return client.Count().Index(index).Query(query).Do(context.Background())
	})
	if err != nil {
		return 0, 0, nil, err
	}
	countPage := math.Ceil(float64(int(count.(int64)) / size)) //todo 总页数
	res, err := models.InitEs(func(client *elastic.Client) (interface{}, error) {
		return client.Search().Index(index).Query(query).Highlight(high).From((page - 1) * size).Size(size).Do(context.Background())
	})
	return page, int(countPage), res, err
}

// EsList todo es数据处理
func EsList(res *elastic.SearchResult) []*video.VideoList {
	var list []map[string]interface{}
	for _, hit := range res.Hits.Hits {
		var data map[string]interface{}
		json.Unmarshal(hit.Source, &data)
		for i, v := range hit.Highlight {
			data[i] = v[0]
		}
		list = append(list, data)
	}
	var VideoList []*video.VideoList
	for _, v := range list {
		var video = &video.VideoList{
			Title:    v["video_title"].(string),
			SubTitle: v["sub_title"].(string),
			TypeId:   int64(v["video_type"].(float64)),
			Address:  v["address"].(string),
			Video:    v["video_url"].(string),
			Img:      v["imt_url"].(string),
			Userid:   int64(v["userid"].(float64)),
		}
		VideoList = append(VideoList, video)
	}
	return VideoList
}
